'use strict'

const { TaiSpider } = require('tai-spider');
const { hash, formatDate, formatTime } = require('../utils/str-helper');

class SpaceflightnowLaunchSpider extends TaiSpider {

    constructor(options = {}) {
        super(options);
        this.name = 'spaceflightnow-launch-schedule';
        this.debug = true;
        this.start_urls = [
            'https://spaceflightnow.com/launch-schedule/',
        ];
    }

    parseLaunchTime(data) {
        let compStr = ''
        for (let s of data) {
            if (s.startsWith('Launch site:')) break;
            compStr = compStr + s
        }
        return compStr.substring('Launch time: '.length)
    }

    parseLaunchSite(data) {
        for (let s of data) {
            if (s.startsWith('Launch site:')) {
                return s.substring('Launch site: '.length)
            }
        }
        return ''
    }

    *parse(response) {
        // let firstPara = response.css('.entry-content p').get(0);
        // yield* response.follow_all(firstPara.css('a'))

        const currentDate = Date.now()
        let idx = 0
        for (let ele of response.css('.mh-content .datename')) {
            let missiondata = ele.next('.missiondata').extract().split('\n');
            idx += 1
            let launchDate = ele.css('.launchdate').extract_first()
            // let d = formatDate(launchDate)
            yield {
                index_name: 'tai-spaceflightnow-launch-schedule',
                id: hash(missiondata.join()),
                idx: idx.toString().padStart(4,'0'),
                batchName: currentDate.toString().padStart(12, '0'),
                launchdate: launchDate,
                mission: ele.css('.mission').extract_first(),
                launchtime: formatTime(this.parseLaunchTime(missiondata)),
                launchsite: this.parseLaunchSite(missiondata),
                description: ele.next('.missdescrip').extract(),
                refers: ele.next('.missdescrip').css('a').extract_attr('href'),
            }
        }
    }

}

module.exports = SpaceflightnowLaunchSpider;